<!doctype html>
<html>
  <head>
    <title>PGlite Live Incremental Query Example</title>
    <link rel="stylesheet" href="./styles.css" />
    <script src="./utils.js"></script>
    <script type="importmap">
      {
        "imports": {
          "@electric-sql/pglite": "../dist/index.js",
          "@electric-sql/pglite/live": "../dist/live/index.js"
        }
      }
    </script>
    <style>
      #output {
        font-family: monospace;
        overflow: auto;
        max-height: 250px;
        border: 1px solid #eee;
        border-radius: 0.5rem;
        padding: 10px;
        margin: 1rem 0;
        font-size: 9px;
        line-height: 11px;
      }
      button {
        margin: 0 0.5rem 0 0;
      }
    </style>
  </head>
  <body>
    <h1>PGlite Live Incremental Query Example</h1>
    <button id="start">start</button><button id="add" disabled>Add</button>
    <div id="output"></div>
    <div class="script-plus-log">
      <script type="module">
        import { PGlite } from '@electric-sql/pglite'
        import { live } from '@electric-sql/pglite/live'

        const output = document.getElementById('output')
        const startBtn = document.getElementById('start')
        const addBtn = document.getElementById('add')
        let counter = 1000
        let lastClicked = 0
        const nameLength = 10000
        const nameSuffix = '-'.repeat(nameLength)

        const pg = new PGlite({
          extensions: {
            live,
          },
        })
        window.pg = pg

        await pg.exec(`
  CREATE TABLE IF NOT EXISTS test (
    id SERIAL PRIMARY KEY,
    rand FLOAT,
    name TEXT
  );
  INSERT INTO test (name, rand)
  SELECT 'test' || i || '${nameSuffix}', random()
  FROM generate_series(1, ${counter}) AS i;
`)

        startBtn.addEventListener('click', async () => {
          lastClicked = performance.now()
          startBtn.disabled = true
          addBtn.disabled = false
          pg.live.incrementalQuery(
            'SELECT * FROM test ORDER BY rand;',
            null,
            'id',
            (res) => {
              const time = performance.now() - lastClicked
              console.log(`Update took ${time}ms`)
              output.textContent = res.rows.map((row) => row.id).join(', ')
            },
          )
        })

        addBtn.addEventListener('click', async () => {
          lastClicked = performance.now()
          await pg.query(
            'INSERT INTO test (name, rand) VALUES ($1, random());',
            [`test${++counter}${nameSuffix}`],
          )
        })
      </script>
      <div id="log"></div>
    </div>
  </body>
</html>
